{% extends 'base_children.html' %}
{% block self_head %}
<link  rel="stylesheet" href="/static/larryms/thirdlib/formSelects-v4.css" >


{% endblock %}
{% block content %}
    <div class="layui-fluid form-demo-box">

        <div class="layui-row">
            <div class="layui-col-lg12">

                <section>
                    <div class="layui-col-md7">

                        <div class="layui-card">
                            <div class="layui-card-header">

                                <strong>ansible模块</strong>

                            </div>

                            <div class="layui-card-body" style="height: 600px;">
                                <form class="layui-form layui-form-pane" id="ansibleModelRun" lay-filter="layui-form" action="{% url 'ansible_exe_modules' %}">

                                    <div class="layui-form-item">
                                        <label class="layui-form-label">产品线</label>
                                        <div class="layui-input-block">
                                            <select name="prod_line" xm-select='prod_line'  xm-select-radio>
                                                    <option value="">liandongduoxuan</option>
                                            </select>
{#                                             <input type="text" id="yewuxian" class="layu=3i-input" readonly="readonly">#}
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">目标机器</label>
                                        <div class="layui-input-block">
                                            <select name='hosts' id="select_host" xm-select='select_host'  xm-select-max="3">
                                                    <option value="">选择一个服务器</option>
                                            </select>

                                        </div>
                                    </div>



{#                                    //这里可以调用ansble de 执行uuid#}
                                    <input  type="hidden"   class="form-control" id="ans_uuid" name="ans_uuid" value="{{ans_uuid}}">

                                    <div class="layui-form-item">
                                        <label class="layui-form-label">模块选择</label>
                                        <div class="layui-input-inline">
                                            {#                                    onchange="oBtAnsibleModel();" #}
                                            <select name="ansible_model" lay-filter="ansible_model" id="ansible_model">
                                                <option value="ping">ping</option>
                                                <option value="raw">shell</option>
                                                <option value="yum">yum</option>
                                                <option value="copy">copy</option>
                                                <option value="service" name="ansible_model">service</option>
                                                <option value="file" name="ansible_model">file</option>
                                                <option value="user" name="ansible_model">user</option>
                                                <option value="synchronize" name="ansible_model">sync</option>
                                                <option value="cron" name="ansible_model">cron</option>
                                                <option value="get_url" name="ansible_model">wget</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="layui-form-item">
                                        <label class="layui-form-label">模块参数:</label>
                                        <div class="layui-input-block">
                                            <input class="layui-input larryms-input" id="ansible_args" type="text"
                                                   name="ansible_args" autocomplete="off" placeholder="模块参数" value="">
                                        </div>
                                    </div>

                                    <div class="layui-form-item">
                                        <label class="layui-form-label">调试模式</label>
                                        <div class="layui-input-block">
                                            <input type="checkbox" name="ans_debug" lay-skin="switch" value="ON"  lay-text="ON|OFF">
                                        </div>
                                    </div>
            {% csrf_token %}

                                    <div class="layui-form-item">
                                        <div class="layui-input-block">
                                            <button type="button" lay-submit="" lay-filter='canceljob'
                                                    class="layui-btn layui-btn-danger">撤销
                                            </button>

                                            <button type="button" class="layui-btn layui-btn-normal" lay-submit="" lay-filter='runjob' id="run_ansible_model">执行
                                            </button>

                                        </div>
                                    </div>
                                </form>
                            </div>

                        </div>
                    </div>


                    <div class="layui-col-md5">

                        <div class="layui-card">
                            <div class="layui-card-header">

                                <strong>执行结果</strong>

                            </div>
                            <div class="layui-card-body">

                                <div class="html">
                                    <div id="result">
                                    </div>
                                </div>
                            </div>

                        </div>

                    </div>
                </section>


            </div>

        </div>
    </div>


{% endblock %}

{% block self_foot %}
    <script type="text/javascript">
        layui.config({
            version: "2.0.8",
            base: '/static/larryms/',
            {#layertype:2#}
        }).extend({
            larry: 'js/base'
        }).use(['larry', 'layer', 'jquery', 'larryms', 'form','formSelects'], function () {
            var $ = layui.$,
                larry = layui.larry,
                form = layui.form,
                layer = layui.layer,
                formSelects = layui.formSelects,
                larryms = layui.larryms;

            {#var curIfr = parent.layer.getFrameIndex(window.name);#}
             form.on('select(ansible_model)', function (data) {
                console.log(data);
                var value = data.value;

                {#     var obj = document.getElementById("ansible_model");#}
                {#var index = obj.selectedIndex;#}
                {#var value = obj.options[index].value;#}
                if (value == "raw") {
                    document.getElementById("ansible_args").value = "uptime";
                }
                else if (value == "yum") {
                    document.getElementById("ansible_args").value = "name=httpd state=present";

                }
                else if (value == "service") {
                    document.getElementById("ansible_args").value = "name=httpd state=restarted enabled=yes";

                }
                else if (value == "cron") {
                    document.getElementById("ansible_args").value = 'name="sync time" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate window.time.com"';

                }
                else if (value == "file") {
                    document.getElementById("ansible_args").value = 'src=/root/test.txt dest=/tmp/test.txt owner=root group=root mode=700 state=touch';
                }
                else if (value == "copy") {
                    document.getElementById("ansible_args").value = 'src=/root/test.txt dest=/tmp/test.txt';
                }
                else if (value == "user") {
                    document.getElementById("ansible_args").value = "name=welliam password='$6yshUMNL8dhY'";

                }
                else if (value == "synchronize") {
                    document.getElementById("ansible_args").value = 'src=/root/a dest=/tmp/ compress=yes rsync_opts="--exclude=.git --exclude=static/image"';
                }
                else if (value == "get_url") {
                    document.getElementById("ansible_args").value = "url=http://url/test.tar.gz dest=/tmp";

                }
                else if (value == "ping") {
                    document.getElementById("ansible_args").value = "";
                }
                else {
                    document.getElementById("ansible_args").value = "";
                }

            });



            form.on('submit(canceljob', function (data) {
                    larryms.msg('取消任务还没开发')
                }
            );


            form.on('submit(runjob)', function (data) {
                console.log(data.field)
                var btnObj = $(data);
                btnObj.attr('disabled', true);
                var form = document.getElementById('ansibleModelRun');
                var post_data = {};
                for (var i = 1; i < form.length; ++i) {
                    var name = form[i].name;
                    var value = form[i].value;
                    var project = name.indexOf("ansible_model");
                    if (project == 0 && value.length == 0 && name != "ansible_args") {
                        larryms.msg('注意必添项不能为空')
                        btnObj.removeAttr('disabled');
                        return false;
                    }
                }
                ;
                $("#result").html("服务器正在处理，请稍等。。。");
                /* 轮训获取结果 开始  */
                var interval = setInterval(function () {
                    $.ajax({
                        url: '{% url 'get_ans_run_result' %}',
                        type: 'post',
                        data: data.field,
                        success: function (result) {
                            if (result["msg"] !== null) {
                                $("#result").append("<p>" + result["msg"] + "</p>");
                                {#document.getElementById("scrollToTop").scrollIntoView();#}
                                if (result["msg"].indexOf("[Done]") == 0) {
                                    clearInterval(interval);
                                    larryms.msg("Ansible执行完成");
                                    btnObj.removeAttr('disabled');
                                }
                            }
                        },
                        error: function (response) {
                            btnObj.removeAttr('disabled');
                            clearInterval(interval);
                        }
                    });
                }, 500);  //一秒钟运行2此

// 	    /* 轮训获取结果结束  */
                $.ajax({
                    dataType: "text",
                    url: '{% url 'ansible_exe_modules' %}', //请求地址
                    type: "POST",  //提交类似
                      {#contentType: "application/json",#}
                    data: data.field,  //提交参数
                    success: function (res) {
                        btnObj.removeAttr('disabled');
                        if (res["code"] == "500") {
                            clearInterval(interval);
                            btnObj.removeAttr('disabled');
                            larryms.msg(res["msg"]);
                        }

                    },
                    error: function (response) {
                        btnObj.removeAttr('disabled');
                        larryms.msg("运行失败" );
                        clearInterval(interval);
                    }
                });


            });


            formSelects.config('prod_line', {
    type: 'get',                //ÇëÇó·½Ê½: post, get, put, delete...
    header: {},                 //×Ô¶¨ÒåÇëÇóÍ·
    data: {},                   //×Ô¶¨Òå³ýËÑË÷ÄÚÈÝÍâµÄÆäËûÊý¾Ý
    searchUrl: '{% url 'get_json_tree' %}',
    searchName: 'keyword',      //×Ô¶¨ÒåËÑË÷ÄÚÈÝµÄkeyÖµ
    searchVal: '',              //×Ô¶¨ÒåËÑË÷ÄÚÈÝ, ËÑËØÒ»´ÎºóÊ§Ð§, ÓÅÏÈ¼¶¸ßÓÚËÑË÷¿òÖÐµÄÖµ
    keyName: 'name',            //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐnameµÄkey, Ä¬ÈÏ name
    keyVal: 'value',            //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐvalueµÄkey, Ä¬ÈÏ value
    keySel: 'selected',         //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐselectedµÄkey, Ä¬ÈÏ selected
    keyDis: 'disabled',         //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐdisabledµÄkey, Ä¬ÈÏ disabled
    keyChildren: 'children',    //Áª¶¯¶àÑ¡×Ô¶¨Òåchildren
    delay: 500,                 //ËÑË÷ÑÓ³ÙÊ±¼ä, Ä¬ÈÏÍ£Ö¹ÊäÈë500msºó¿ªÊ¼ËÑË÷
    direction: 'auto',          //¶àÑ¡ÏÂÀ­·½Ïò, auto|up|down
    response: {
        statusCode: 0,          //³É¹¦×´Ì¬Âë
        statusName: 'code',     //code key
        msgName: 'msg',         //msg key
        dataName: 'data'        //data key
    },
    success: function(id, url, searchVal, result){      //Ê¹ÓÃÔ¶³Ì·½Ê½µÄsuccess»Øµ÷
        console.log(id);        //×é¼þID xm-select
        console.log(url);       //URL
        console.log(searchVal); //ËÑË÷µÄvalue
        console.log(result);    //·µ»ØµÄ½á¹û
    },
    error: function(id, url, searchVal, err){           //Ê¹ÓÃÔ¶³Ì·½Ê½µÄerror»Øµ÷
        //
        console.log(err);   //err¶ÔÏó
    },
    beforeSuccess: function(id, url, searchVal, result){

        result.data=JSON.parse(result.data)
        return result;  //±ØÐëreturnÒ»¸ö½á¹û, Õâ¸ö½á¹ûÒª·ûºÏ¶ÔÓ¦µÄÊý¾Ý½á¹¹
    },
    beforeSearch: function(id, url, searchVal){         //ËÑË÷Ç°µ÷ÓÃ´Ë·½·¨, return true½«´¥·¢ËÑË÷, ·ñÔò²»´¥·¢
        if(!searchVal){//Èç¹ûËÑË÷ÄÚÈÝÎª¿Õ,¾Í²»´¥·¢ËÑË÷
            return false;
        }
        return true;
    },
    clearInput: false,          //µ±ÓÐËÑË÷ÄÚÈÝÊ±,  µã»÷Ñ¡ÏîÊÇ·ñÇå¿ÕËÑË÷ÄÚÈÝ, Ä¬ÈÏ²»Çå¿Õ
   }, true);
            formSelects.data('prod_line','server',{
                url: '{% url 'get_json_tree' %}',

                 linkage: true,
                linkageWidth:130,
                 keyChildren: 'children',
                keyName: 'name',
                keyVal: 'value',
                 success: function(result){
						        console.log(result);
						    },
                 error: function(err){           //Ê¹ÓÃÔ¶³Ì·½Ê½µÄerror»Øµ÷
						        //Í¬ÉÏ
						        console.log(err);   //err¶ÔÏó
						    },


            });

          formSelects.on('prod_line', function(id, vals, val, isAdd, isDisabled){
              var hostids='';
              for(var i in vals)
              {
                  var  hostname=vals[i].name.split('/').pop();
                  var hostid=vals[i].value.split('/').pop();
                  if (hostname ==='host')
                  {
	   $('#select_host option:selected').empty();

		   if ( hostid > 0){
				{#$.ajax({#}
				{#	dataType: "JSON",#}
				{#	url:'/cmdb/get_json_tree_host/'+ hostid + '/', //请求地址#}
				{#	type:"GET",  //提交类似#}
                    {#data: {"hostid":hostid},#}
				{#	success: function(res){#}
                {##}
				{#		var headHtml = '<select name="hosts" id="select_host" xm-select="select_host" xm-select-max="3">';#}
                {##}
				{#		var optionhtml = '';#}
				{#		for (var i=0; i <res.data.length; i++){#}
				{#			 optionhtml += '<option  value="' + res.data[i]["id"] +  '"> ' + res.data[i]["hostname"] + '</option>'#}
				{#		};#}
				{#		  var  selecthtml =  headHtml + optionhtml + '</select>';#}
				{#		document.getElementById("select_host").innerHTML= selecthtml;#}
                {##}
				{#	},#}
                {#      error: function (response) {#}
                {#                        larryms.alert(response.responseText);#}
                {#                    }#}
				{# });#}
  formSelects.config('select_host', {
    type: 'get',                //ÇëÇó·½Ê½: post, get, put, delete...
    header: {},                 //×Ô¶¨ÒåÇëÇóÍ·
    data: {},                   //×Ô¶¨Òå³ýËÑË÷ÄÚÈÝÍâµÄÆäËûÊý¾Ý
    searchUrl: '',           //ËÑË÷µØÖ·, Ä¬ÈÏÊ¹ÓÃxm-select-searchµÄÖµ, ´Ë²ÎÊýÓÅÏÈ¼¶¸ß
    searchName: 'keyword',      //×Ô¶¨ÒåËÑË÷ÄÚÈÝµÄkeyÖµ
    searchVal: '',              //×Ô¶¨ÒåËÑË÷ÄÚÈÝ, ËÑËØÒ»´ÎºóÊ§Ð§, ÓÅÏÈ¼¶¸ßÓÚËÑË÷¿òÖÐµÄÖµ
    keyName: 'name',            //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐnameµÄkey, Ä¬ÈÏ name
    keyVal: 'value',            //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐvalueµÄkey, Ä¬ÈÏ value
    keySel: 'selected',         //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐselectedµÄkey, Ä¬ÈÏ selected
    keyDis: 'disabled',         //×Ô¶¨Òå·µ»ØÊý¾ÝÖÐdisabledµÄkey, Ä¬ÈÏ disabled

    delay: 500,                 //ËÑË÷ÑÓ³ÙÊ±¼ä, Ä¬ÈÏÍ£Ö¹ÊäÈë500msºó¿ªÊ¼ËÑË÷
    direction: 'auto',          //¶àÑ¡ÏÂÀ­·½Ïò, auto|up|down
    response: {
        statusCode: 0,          //³É¹¦×´Ì¬Âë
        statusName: 'code',     //code key
        msgName: 'msg',         //msg key
        dataName: 'data'        //data key
    },
    success: function(id, url, searchVal, result){      //Ê¹ÓÃÔ¶³Ì·½Ê½µÄsuccess»Øµ÷
        console.log(id);        //×é¼þID xm-select
        console.log(url);       //URL
        console.log(searchVal); //ËÑË÷µÄvalue
        console.log(result);    //·µ»ØµÄ½á¹û
    },
    error: function(id, url, searchVal, err){           //Ê¹ÓÃÔ¶³Ì·½Ê½µÄerror»Øµ÷
        //
        console.log(err);   //err¶ÔÏó
    },
    beforeSuccess: function(id, url, searchVal, result){

        result.data=JSON.parse(result.data)
        return result;  //±ØÐëreturnÒ»¸ö½á¹û, Õâ¸ö½á¹ûÒª·ûºÏ¶ÔÓ¦µÄÊý¾Ý½á¹¹
    },
    beforeSearch: function(id, url, searchVal){         //ËÑË÷Ç°µ÷ÓÃ´Ë·½·¨, return true½«´¥·¢ËÑË÷, ·ñÔò²»´¥·¢
        if(!searchVal){//Èç¹ûËÑË÷ÄÚÈÝÎª¿Õ,¾Í²»´¥·¢ËÑË÷
            return false;
        }
        return true;
    },
    clearInput: false,          //µ±ÓÐËÑË÷ÄÚÈÝÊ±, µã»÷Ñ¡ÏîÊÇ·ñÇå¿ÕËÑË÷ÄÚÈÝ, Ä¬ÈÏ²»Çå¿Õ
}, true);
				formSelects.data('select_host', 'server', {
    url: '/cmdb/get_json_tree_host/'+ hostid ,

});
		   };

                  }
                  else{
                      larryms.alert('最后的节点要是host，才能选出主机奥');
                      formSelects.value('prod_line',[vals[i].value],false) ;//删掉这个值
                  }
                  console.log(hostname);
                  console.log(hostid)

              };
        }, true);


        });


    </script>


    <script type="text/javascript">
        {##}
        {##}
        {#function oBtInventorySelect(obj){#}
        {#	   var obj = document.getElementById("ansible_inventory");#}
        {#	   var index = obj.selectedIndex;#}
        {#	   var sId = obj.options[index].value;#}
        {#	   if ( sId  > 0){#}
        {#			$.ajax({#}
        {#				dataType: "JSON",#}
        {#				url: "/api/inventory/" + sId +"/", //请求地址#}
        {#				type:"GET",  //提交类似#}
        {#				success:function(response){#}
        {#					if ( JSON.stringify(response["data"]) != '{}'){#}
        {#						$.notify({#}
        {#							title: "<strong>发现资产:</strong>",#}
        {#							message:  "<pre>" + JSON.stringify(response["data"],null,4) + "</pre>",#}
        {#						},#}
        {#						{#}
        {#							type: 'success',#}
        {#							timer: 3000,#}
        {#							delay: 30000#}
        {#						});#}
        {#					}#}
        {#					else {#}
        {#						$.notify({#}
        {#							title: "<strong>Ops：</strong>",#}
        {#							message: "该条件下未发现资产~"#}
        {#						},#}
        {#						{#}
        {#							type: 'danger'#}
        {#						});#}
        {#					}#}
        {##}
        {##}
        {#				},#}
        {#			});#}
        {#	   }#}
        {# } #}
            {##}
            {##}
            {##}
            {##}
            {#function oBtServiceSelect(model,ids){#}
            {#	   var obj = document.getElementById(ids);#}
            {#	   var index = obj.selectedIndex;#}
            {#	   var sId = obj.options[index].value;#}
            {#	   if ( sId  > 0){#}
            {#			$.ajax({#}
            {#				dataType: "JSON",#}
            {#				url:'/assets_server/', //请求地址#}
            {#				type:"POST",  //提交类似#}
            {#				data:{#}
            {#					"query":model,#}
            {#					"id":sId#}
            {#				},#}
            {#				success:function(response){#}
            {#					var sHtml = '';#}
            {#					for (var i=0; i <response["data"].length; i++){#}
            {#						sHtml += '<br>' + response["data"][i]["ip"] + " | " + response["data"][i]["project"] + " | " + response["data"][i]["service"]#}
            {#					};#}
            {#					if ( sHtml.length > 0){#}
            {#						$.notify({#}
            {#							title: "<strong>发现主机:</strong>",#}
            {#							message: sHtml#}
            {#						},#}
            {#						{#}
            {#							type: 'info'#}
            {#						});#}
            {#						$('#run_ansible_model').removeAttr("disabled");#}
            {#					}#}
            {#					else {#}
            {#						$.notify({#}
            {#							title: "<strong>Ops：</strong>",#}
            {#							message: "该条件下未发现主机资源~"#}
            {#						},#}
            {#						{#}
            {#							type: 'danger'#}
            {#						});#}
            {#						$('#run_ansible_model').attr("disabled",true);#}
            {#					}#}
            {##}
            {##}
            {#				},#}
            {#			});#}
            {#	   }#}
            {#	   else{#}
            {#		   $('#server option:selected').empty();#}
            {#		   $('#server').attr("disabled",true);#}
            {#	   }#}
            {##}

        {##}




        {#{% if errorInfo %}#}
        {#	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);#}
        {#{% endif %}#}
    </script>



{% endblock %}